package com.thejoyrun.retrofit.presenter.user;

import com.thejoyrun.retrofit.bean.User;
import com.thejoyrun.retrofit.http.NetRetrofit;
import com.thejoyrun.retrofit.model.user.UserDAO;
import com.thejoyrun.retrofit.model.user.UserService;
import com.thejoyrun.retrofit.view.UserView;

import java.util.List;

import rx.functions.Action1;
import rxjava.AndroidSchedulers;
import rxjava.SimpleSubscriber;

/**
 * Created by kkmike999 on 2016/05/08.
 */
public class UserPresenterImpl implements UserPresenter {
	UserService userService;
	UserDAO     userDAO;
	UserView    userView;

	public UserPresenterImpl(UserView userView) {
		this.userView = userView;

		userService = new NetRetrofit().create(UserService.class);
		userDAO = new UserDAO();
	}

	public UserPresenterImpl(UserService userService, UserDAO userDAO, UserView userView) {
		this.userService = userService;
		this.userDAO = userDAO;
		this.userView = userView;
	}

	@Override
	public void loadUser(int uid) {
		userService.loadUser(uid)
		           .doOnNext(new Action1<User>() {
			           @Override
			           public void call(User user) {
				           userDAO.save(user);
			           }
		           })
		           .observeOn(AndroidSchedulers.mainThread())
		           .subscribe(new SimpleSubscriber<User>() {
			           @Override
			           public void onNext(User user) {
				           userView.onUserLoaded(user);
			           }
		           });
	}

	@Override
	public void loadUserList() {
		userService.loadUserList()
		           .doOnNext(new Action1<List<User>>() {
			           @Override
			           public void call(List<User> users) {
				           userDAO.save(users);
			           }
		           })
		           .observeOn(AndroidSchedulers.mainThread())
		           .subscribe(new SimpleSubscriber<List<User>>() {
			           @Override
			           public void onNext(List<User> users) {
				           userView.onUserListLoaded(users);
			           }
		           });
	}
}
